package com.petrochina.cloudconfig.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileUtil {


    /**
     * 迭代删除文件
     * @param path
     */
    public static void deleteFile(String path){
        File file = new File(path);
        if(file.exists()){
            if(file.isDirectory()){
                File[] subFiles = file.listFiles();
                if(subFiles.length > 0){
                    //删除子文件
                    for (int i = 0; i < subFiles.length; i++) {
                        FileUtil.deleteFile(subFiles[i].getAbsolutePath());
                    }
                }
            }
            file.delete();
        }
    }


    /**
     * 返回文件到reponse
     * @param response
     * @param file
     */
    public static void saveFileToResponse(HttpServletResponse response, File file) {

        if (file.exists()) {
            response.setContentType("application/octet-stream");//
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" +  file.getName());// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
